//
//  BaseWebViewController.m
//  Root
//
//  Created by scho on 2019/1/10.
//  Copyright © 2019 Root. All rights reserved.
//

#import "BaseWebViewController.h"
#import <AFNetworking/AFNetworking.h>
#import <AFNetworking/UIKit+AFNetworking.h>

#import "Reachability.h"

@interface BaseWebViewController ()

@property (nullable, strong, nonatomic, readwrite) WKWebView *webView;
@property (nullable, strong, nonatomic) UIProgressView *progressView;
//
@property (nullable, strong, nonatomic) NSLayoutConstraint *topConstraint;
@property (nullable, strong, nonatomic) NSLayoutConstraint *bottomConstraint;

@end

@implementation BaseWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.webTitle;
    
    [self setupWebView];
    [self setupProgressView];
    // kvo
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    // check network status
    if([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable) {
        // tip
        [self.view showHUDWithText:QISNotConnectedToInternetTip delayHide:1.0];
        return ;
    }
    else if (_urlString.length > 0 || _url != nil) {
        [self startLoadRequest];
    }
}

- (void)dealloc
{
    // kvo
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    
    if (self.webView.isLoading) {
        [self.webView stopLoading];
        
        // hide
        [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
    }
}

// helper
- (void)setupWebView
{
    // web view
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.preferences.minimumFontSize = 11;
    
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
    _webView.navigationDelegate = self;
    _webView.UIDelegate = self;
    
    [self.view addSubview:_webView];
    
    _webView.translatesAutoresizingMaskIntoConstraints = NO; // use auto layout
    // auto layout web view
    [self.view pinSubview:_webView toEdge:NSLayoutAttributeLeading];
    [self.view pinSubview:_webView toEdge:NSLayoutAttributeTrailing];
    self.topConstraint = [self.view pinSubview:_webView toEdge:NSLayoutAttributeTop offset:_top];
    self.bottomConstraint = [self.view pinSubview:_webView toEdge:NSLayoutAttributeBottom offset:_bottom];
}

- (void)setupProgressView
{
    const CGFloat height = 2.0;
    CGRect rect = self.view.bounds;
    rect.size.height = height;
    
    self.progressView = [[UIProgressView alloc] initWithFrame:rect];
    _progressView.tintColor = UIColorFromRGB(0x8080FC);
    _progressView.trackTintColor = [UIColor lightGrayColor];
    [self.view addSubview:_progressView];
    
    // auto layout
    _progressView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view pinSubview:_progressView toEdge:NSLayoutAttributeLeading];
    [self.view pinSubview:_progressView toEdge:NSLayoutAttributeTrailing];
    [self.view pinSubview:_progressView toEdge:NSLayoutAttributeTop];
    [_progressView pinViewHeight:height];
}

// adjust top and bottom of web view.
- (void)adjustWebViewWithTop:(CGFloat)top bottom:(CGFloat)bottom {
    CGFloat topOffset = -top;
    CGFloat bottomOffset = bottom;
    self.topConstraint.constant = topOffset;
    self.bottomConstraint.constant = bottomOffset;
    
    // update
    [self.view setNeedsUpdateConstraints];
    [self.view updateConstraintsIfNeeded];
}

#pragma mark - KVO
// for progress view
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            [self.progressView setProgress:1.0 animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.hidden = YES;
                [self.progressView setProgress:0 animated:NO];
            });
            
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}

#pragma mark - access method

- (void)setUrlString:(NSString *)urlString
{
    _urlString = urlString;
    
    if (_urlString.length > 0) {
        [self startLoadRequest];
    }
}

// helper
- (void)startLoadRequest
{
    self.navigationItem.rightBarButtonItems = nil; //reset
    
    if (_webView != nil) { // if did call viewDidLoad
        // load page
        NSURL *url = nil;
        if (_urlString.length > 0 && ([_urlString hasPrefix:@"http://"] || [_urlString hasPrefix:@"https://"])) {
            url = [NSURL URLWithString:_urlString];
        }else {
            url = _url;
        }
        
        NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
        
        // for vendor link
        if (self.customHttpHeaderInfo.count > 0) {
            NSArray *keys = self.customHttpHeaderInfo.allKeys;
            NSString *value = nil;
            for (NSString *key in keys) {
                value = _customHttpHeaderInfo[key];
                if (value != nil) {
                    [urlRequest setValue:value forHTTPHeaderField:key];
                }
            }//for
        }
        
        [self.webView loadRequest:urlRequest];
    }
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
    // show network activiety indicator
    [[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    // hide
    [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
    
    // set title
    if (self.isUseH5Title) {
        NSString *js = @"document.title";
        [webView evaluateJavaScript:js completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            if(error == nil && [result isKindOfClass:[NSString class]]) {
                self.title = result;
            }
        }];
    }
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    // hide
    [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
    
    [self showRequestFailureWithError:error];
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler{
    WKNavigationActionPolicy policy =WKNavigationActionPolicyAllow;
    NSSet *validSchemes = [NSSet setWithArray:@[@"http", @"https"]];
    if(![validSchemes containsObject:navigationAction.request.URL.scheme]) {
        
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        policy =WKNavigationActionPolicyCancel;
    }else if([[navigationAction.request.URL host] isEqualToString:@"itunes.apple.com"] &&[[UIApplication sharedApplication] openURL:navigationAction.request.URL]){
        policy =WKNavigationActionPolicyCancel;
    }
    decisionHandler(policy);
}

// helper
- (void)showRequestFailureWithError:(NSError*)error
{
    // Error
    
    NSString *errorText = @"网络出现异常";
    if ([error.domain isEqualToString:NSURLErrorDomain] && (error.code == NSURLErrorCannotConnectToHost || error.code == NSURLErrorNetworkConnectionLost)) {
        errorText = [error.localizedDescription stringByRemovingPercentEncoding];
        if (errorText.length == 0) { // nil or @""
            errorText = @"网络无法连接";
        }
        else if (errorText.length > 32) {
            // too more text
            errorText = @"网络无法连接";
        }
    }
    else if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorNotConnectedToInternet) {
        errorText = QISNotConnectedToInternetTip;
    }
    else if (error.code == NSURLErrorTimedOut) {
        errorText = @"请求超时";
    }else if (error.code == NSURLErrorCancelled) {//v 5.8.3 取消请求
        errorText = @"";
        return;
    }
    
    // show error
    [self.view showHUDWithText:errorText delayHide:1.0];
}

#pragma mark - WKUIDelegate
//show alert
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message?:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"Complete" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

@end
